package com.hcb.tonguetiphealth.widget.resbook;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.baidu.location.LocationClient;
import com.hcb.tonguetiphealth.adapter.ResListAdapter;
import com.hcb.tonguetiphealth.adapter.SelectionListAdapter;
import com.hcb.tonguetiphealth.global.Global;
import com.hcb.tonguetiphealth.manager.FoodTypeManager;
import com.hcb.tonguetiphealth.manager.JSONManager;
import com.hcb.tonguetiphealth.manager.Location;
import com.hcb.tonguetiphealth.model.Restaurant;
import com.hcb.tonguetiphealth.util.HttpUtils;
import com.hcb.tonguetiphealth.util.MessageWhat;
import com.hcb.tonguetiphealth.util.StringUtils;
import com.hcb.tonguetiphealth.view.R;
import com.hcb.tonguetiphealth.widget.BottomWidget;
import com.hcb.tonguetiphealth.widget.GeneralWidget;
import com.hcb.tonguetiphealth.widget.more.ChangeCityWidget;

public class RestaurantBookWidget extends GeneralWidget implements OnClickListener {
	private static final String TAG = "ResBookWidget";
	
	private Activity ctx;
	private Handler mHandler , handler;
	private Button btDistance, btType, btOrder,  btRecent;
	private ListView resListView, dialogListView ;
	private List<Restaurant> resList;
	private ResListAdapter resAdapter;
	private String resName, distacne = "999999", foodTypeName = "-1";
	private int type;//type:0表示距离按钮，1表示美食类别按钮、2表示排序按钮
	private List<String> disList = new ArrayList<String>();
	private List<String> orderList = new ArrayList<String>();
	private List<String> foodTypeList = new ArrayList<String>();
	private Map<String, List<String>> foodTypeMap = new HashMap<String, List<String>>(); 
	private String selectedFoodType;
	private boolean needSave = false;
	private FoodTypeManager foodTypeManager;
	private TextView tvTitle;
	private ProgressBar progressBar;
	private LinearLayout llBack, llLocation;
	private List<View>viewList = new ArrayList<View>();
	
	private String city;//城市id
	private Location location;
	private LocationClient mLocClient;
	private String lat;
	private String lng;
	
	private PopupWindow window;
	private PopupWindow popupWindow;
	
	private View footerView;
	private TextView tv_footerMore;
	private ProgressBar pb_footerMore;
	
	public RestaurantBookWidget(Context context) {
		super(context);
		ctx = (Activity)context;
		inflate(context, R.layout.res_book, this); 
		bindView();
		bindEvent();
		resName = ctx.getIntent().getStringExtra("resName");
		new BottomWidget(context, this);
		SharedPreferences preferences = ctx.getSharedPreferences(Global.CITYID,
				0);
		city = preferences.getString(Global.CITYID, Global.defaultCityId);
		
		resList = new ArrayList<Restaurant>();
		resAdapter = new ResListAdapter(ctx, resList);
		resListView.setAdapter(resAdapter);
		
		if (resName == null) {
			tvTitle.setText(R.string.near_res);
			resName = "-1";// 获取不到resName表示从酒楼预订入口或从商家详情进入，resName置为“-1”；获取到了resName表示从快速搜索入口进入
		} else {
			tvTitle.setText(R.string.res_list);
		}
		mHandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				switch(msg.what) {
				case MessageWhat.BAIDU_LAOCATION_START:
					showMessageDialog(ctx, "正在确定您的位置...");
					break;
				case  MessageWhat.BAIDU_LAOCATION_SUCESS:
					mLocClient.stop();
					lat = String.valueOf( location.getLatitude() );
					lng = String.valueOf( location.getLongitude() );
					Global.lat = lat;
					Global.lng = lng;
					initData();
					break;
				case MessageWhat.SHOW_DIALOG:
					showMessageDialog(ctx, "正在获取商家列表...");
					break;
				case MessageWhat.DIMISS_DIALOG:
					resAdapter.notifyDataSetChanged();
					tv_footerMore.setText(R.string.app_list_footer_more_text);
					pb_footerMore.setVisibility(ProgressBar.GONE);
					dismissMessageDialog();
					break;
				case MessageWhat.NETWORK_FAILD:
					try {
						tv_footerMore.setText(R.string.app_list_footer_more_text);
						pb_footerMore.setVisibility(ProgressBar.GONE);
					  dismissMessageDialog();
					} catch (Exception e) {
						// TODO: handle exception
					}
					//Toast.makeText(ctx,  "网络有点不给力哦", Toast.LENGTH_LONG).show();
					showMessage(ctx, R.string.net_faild);
					break;
				case MessageWhat.GETFODDTYPE_SUCESS:
					if (needSave) {
						foodTypeManager.saveFoodType(foodTypeMap);
					}
					SelectionListAdapter adapter = new SelectionListAdapter(ctx,
							foodTypeList);
					dialogListView.setAdapter(adapter);
					progressBar.setVisibility(View.GONE);
					break;
				}
			}
		};
		
		if (Global.lat !=null && Global.lng != null) {
			lat = Global.lat;
			lng = Global.lng;
			initData();
		}else {
			location = new Location(ctx.getApplicationContext(), mHandler);
			mLocClient = location.mLocationClient;
			mHandler.sendEmptyMessage(MessageWhat.BAIDU_LAOCATION_START);
			mLocClient.start();
		}
		
	}
	
	private void bindEvent() {
		handler  = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				int arg2 = msg.what;
				switch (type) {
				case 0://距离
					btDistance.setText(disList.get(arg2));
					switch (arg2) {
					case 0:
						distacne = "1000";
						break;
					case 1:
						distacne = "2000";
						break;
					case 2:
						distacne = "3000";
						break;
					case 3:
						distacne = "4000";
						break;
					case 4:
						distacne = "5000";
						break;
					case 5:
						distacne = "999999";
						break;

					default:
						break;
					}
					resList.clear();
					initData();
					break;
				case 1: 
					foodTypeName = foodTypeMap.get(selectedFoodType).get(arg2);//获取选择的美食分类大类别对应的子类别
					btType.setText(foodTypeName);
					resList.clear();
					initData();
					break;
				case 2:// 排序,排序分类为人均(0)、距离(1)
					switch (arg2) {
					case 0:
						ComparatorLevel cl = new ComparatorLevel(0);
						Collections.sort(resList, cl);
						btOrder.setText("人均");
						break;
					case 1:
						cl = new ComparatorLevel(1);
						Collections.sort(resList, cl);
						btOrder.setText("距离");
						break;

					default:
						break;
					}
					resAdapter.notifyDataSetChanged();
					break;
				default:
					break;
				}
			}
		};
		resListView.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				// TODO Auto-generated method stub
				Restaurant res = (Restaurant) arg0.getAdapter().getItem(arg2);
				if (arg2 == arg0.getAdapter().getCount() - 1) {
					tv_footerMore
							.setText(R.string.app_list_footer_getting_text);
					pb_footerMore.setVisibility(ProgressBar.VISIBLE);
					initData();
				} else {
					//将最近浏览的商家加入到list，不重复添加。
					boolean flag = true;
					for (int i = 0; i < Global.recentResList.size(); i++) {
						Restaurant restaurant = Global.recentResList.get(i);
						if (res.getId().equals(restaurant.getId())) {
							flag = false;
							break;
						}
					}
					if (flag) {
						Global.recentResList.add(res);
					}
					ctx.getIntent().putExtra("resId", res.getId());
					Global.resList = resList;
					ctx.setContentView(new RestaurantBookInfoWidget(ctx));
				}
			}
		});
 	
	}
	
	private void bindView() {
		btDistance = (Button)findViewById(R.id.res_distance_button);
		btType = (Button)findViewById(R.id.res_gourme_type_button);
		btOrder = (Button)findViewById(R.id.near_order_button);
		btRecent = (Button)findViewById(R.id.near_res_recent);
		llBack = (LinearLayout)findViewById(R.id.res_linearlayout_back);
		llLocation = (LinearLayout)findViewById(R.id.res_location_linearlayout);
//		selectionListview = (ListView)findViewById(R.id.selection_listview);
		resListView = (ListView)findViewById(R.id.res_listview);
//		selectionChildListview = (ListView)findViewById(R.id.selection_child_listview);
		tvTitle = (TextView)findViewById(R.id.title_res);
		
		footerView = LayoutInflater.from(ctx).inflate(R.layout.refresh_list_footer, null);
		tv_footerMore = (TextView)footerView.findViewById(R.id.refresh_list_footer_text);
		pb_footerMore = (ProgressBar)footerView.findViewById(R.id.refresh_list_footer_progressbar);
		resListView.addFooterView(footerView);
		
		
		btDistance.setOnClickListener(this);
		btType.setOnClickListener(this);
		btOrder.setOnClickListener(this);
		btRecent.setOnClickListener(this);
		llBack.setOnClickListener(this);
		llLocation.setOnClickListener(this);
		
		disList.add("1千米");
		disList.add("2千米");
		disList.add("3千米");
		disList.add("4千米");
		disList.add("5千米");
		disList.add("全城");
		
		orderList.add("人均");
		orderList.add("距离");
		
		viewList.add(btDistance);
		viewList.add(btType);
		viewList.add(btOrder);
		viewList.add(btRecent);
		
	}
 
	
	public void onClick(View v) {
		setViewBackGround(v);
		switch(v.getId()) {
		case R.id.res_distance_button:
			type = 0;
			popupWindow = makePopupWindow(btDistance,  handler);
			popupWindow.showAsDropDown(btDistance, btDistance.getWidth()/2*-1, 0);
			btType.setText(R.string.near_res_gourme_type);
			foodTypeName = "-1";//值为-1时，不作为查询条件。点击距离后，查询该距离下的所有商家信息。
			break;
		case R.id.res_gourme_type_button:
			type = 1;
		//	showSelectDialog();
			popupWindow = makePopupWindow(btType,  handler);
			popupWindow.showAsDropDown(btType, btType.getWidth()/2*-1, 0);
			getFoodType();
 
			break;
		case R.id.near_order_button:
			type = 2;
			popupWindow = makePopupWindow(btOrder,  handler);
			popupWindow.showAsDropDown(btOrder, btOrder.getWidth()/2*-1, 0);
//			showSelectDialog();
			break;
		case R.id.near_res_recent:
			resList = Global.recentResList;
			resAdapter = new ResListAdapter(ctx, resList);
			resListView.setAdapter(resAdapter);
			break;
		case R.id.res_linearlayout_back:
			ctx.finish();
			break;
		case R.id.res_location_linearlayout:
			ctx.getIntent().putExtra("fromWidget", "RestaurantBookWidget");
			ctx.setContentView(new ChangeCityWidget(ctx));
			
			break;
		default:
			break;
		}
	}
 
	private void  setViewBackGround(View v){
		for (int i = 0; i < viewList.size(); i++) {
			View v1 = viewList.get(i);
			if (v == v1) {
				v1.setBackgroundResource(R.drawable.title_bg_active);//选中设置为高亮
			}else {
				v1.setBackgroundResource(R.drawable.title_bg);
			}
		}
	}
	
	private void getFoodType(){
		//首先从本地数据库获取美食分类，获取不到，从网络下载
		foodTypeManager = new FoodTypeManager(ctx);
		foodTypeList = new ArrayList<String>();
		foodTypeMap = new HashMap<String, List<String>>();
		foodTypeMap  = foodTypeManager.getFoodTypeMap();
		foodTypeList = foodTypeManager.getFoodTypeList();
		if (foodTypeList.size() == 4) {
			needSave = false;
			mHandler.sendEmptyMessage(MessageWhat.GETFODDTYPE_SUCESS);
			return;
		}
		needSave = true;
		new Thread(){
			public void run() {
				String response = null;
				try {
					response = HttpUtils.doGet(Global.getServletfoodtype());
				} catch (ClientProtocolException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				 
				foodTypeList = new ArrayList<String>();
				foodTypeMap = new HashMap<String, List<String>>();
				JSONManager jsonManager = new JSONManager();
				if (jsonManager.isGotJSONObject(response)) {
					int result = jsonManager.getResult();
					JSONArray jsonArray = jsonManager.getJsonList();
					for (int i = 0; i < jsonArray.length() && i<result; i++) {
						JSONObject obj;
						try {
							obj = jsonArray.getJSONObject(i);
							String foodType = obj.getString("catname");
							foodTypeList.add(foodType);
							JSONArray jsonArrayChild = obj.getJSONArray("child");
							List<String> list = new ArrayList<String>();
							for (int j = 0; j < jsonArrayChild.length(); j++) {
								JSONObject objchild = jsonArrayChild.getJSONObject(j);
								list.add(objchild.getString("catname"));
							}
							foodTypeMap.put(foodType, list);
							
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						
					}
					mHandler.sendEmptyMessage(MessageWhat.GETFODDTYPE_SUCESS);
				}else {
					mHandler.sendEmptyMessage(MessageWhat.NETWORK_FAILD);
				}
			}
		}.start();
		
	}
	
	
	private void initData() {
		mHandler.sendEmptyMessage(MessageWhat.SHOW_DIALOG);
		new Thread(){
			public void run() {
				List <NameValuePair> params = new ArrayList <NameValuePair>();
				params.add(new BasicNameValuePair("resName",resName));
				params.add(new BasicNameValuePair("lng", lng));
				params.add(new BasicNameValuePair("lat", lat));
				params.add(new BasicNameValuePair("city", city));
				params.add(new BasicNameValuePair("distance", distacne));
				params.add(new BasicNameValuePair("foodTypeName", foodTypeName));
				params.add(new BasicNameValuePair("count", ""+resList.size()));
				System.out.println("size:"+resList.size());
				String result  = HttpUtils.Post(Global.searchResUrl, params);
				System.out.println("result:"+result);
				JSONManager jsonManager = new JSONManager();
				boolean success = jsonManager.isGotJSONObject(result);
				if (success) {
					JSONArray jsonArray = jsonManager.getJsonList();
					int intResult = 0;
					intResult = jsonManager.getResult();
					for(int i=0; jsonArray != null && i<intResult && i < jsonArray.length(); i++) {
						Restaurant res = new Restaurant();
						try {
							JSONObject obj = jsonArray.getJSONObject(i);
							res.setId(obj.getString("userid"));
							res.setName(obj.getString("company"));
							res.setImgURL(obj.getString("thumb"));
							res.setLevel(StringUtils.parseFloat(obj.getString("level")));
							res.setRebate(obj.getString("discount"));
							res.setAvg(obj.getString("rjxf"));
							String labels = getLabels((JSONArray)obj.getJSONArray("cats"));
							res.setLabel(labels);
							res.setDistance(obj.getString("distance"));
					//		res.setGourmeType(obj.getString("gourmeType"));
							resList.add(res);
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
					mHandler.sendEmptyMessage(MessageWhat.DIMISS_DIALOG);
				}else {
					if (result == null) {
						mHandler.sendEmptyMessage(MessageWhat.NETWORK_FAILD);
					}else {
						mHandler.sendEmptyMessage(MessageWhat.DIMISS_DIALOG);
					}
				}
				
			}
		}.start();
		
	}

	private String getLabels(JSONArray jsonArray){
		String labels = "";
		for (int i = 0; jsonArray !=null && i < jsonArray.length(); i++) {
			try {
				JSONObject jsonObject = jsonArray.getJSONObject(i);
				labels += jsonObject.getString("catname") + " ";
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
	//	return labels.equals("") ?"--":labels;
		return labels;
	}
	
	@Override
	public void notifyAdapter() {
		
	}
	
	
	/*public void showSelectDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(ctx); 
        final AlertDialog dialog = builder.create(); 
        builder.setPositiveButton("确定",null);    
        builder.setNegativeButton("取消",null);   
        dialog.setCancelable(true);
        dialog.setCanceledOnTouchOutside(true);
        
        LayoutInflater li = LayoutInflater.from(ctx); 
        View view = li.inflate(R.layout.res_book_dialog_list, null); 
        if (type == 1) {
        	view = li.inflate(R.layout.res_book_dialog_list2, null); 
		}
        dialog.setView(view);
        dialogListView = (ListView)view.findViewById(R.id.selection_listview);
 //       LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams)dialogListView.getLayoutParams();
//      dialogListView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT,
//      LinearLayout.LayoutParams.WRAP_CONTENT));
        final  ListView childView = (ListView)view.findViewById(R.id.selection_child_listview);
        List<String>list = new ArrayList<String>();
        switch (type) {
		case 0:
			list = disList;
			dialog.setTitle("距离");
			SelectionListAdapter adapter = new SelectionListAdapter(ctx, list);
	        dialogListView.setAdapter(adapter);
			break;
		case 1:
			 progressBar = (ProgressBar)view.findViewById(R.id.res_book_dialog_progressbar);
			 progressBar.setVisibility(View.VISIBLE);
			dialog.setTitle("美食类别");
			break;
		case 2:
			list = orderList;
			dialog.setTitle("排序");
			adapter = new SelectionListAdapter(ctx, list);
	        dialogListView.setAdapter(adapter);
			break;

		default:
			break;
		}
        
        dialogListView.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				// TODO Auto-generated method stub
				
				if(null != handler ) {
					if (type != 1) {
						Message msg = new Message();
						msg.what = arg2;
						handler.sendMessage(msg); 
						dialog.dismiss();
					}else {
						childView.setVisibility(View.VISIBLE);
//						dialogListView.setLayoutParams(new LinearLayout.LayoutParams(200,
//				                LinearLayout.LayoutParams.WRAP_CONTENT));
//						childView.setLayoutParams(new LinearLayout.LayoutParams(200,
//				                LinearLayout.LayoutParams.WRAP_CONTENT));
						selectedFoodType = foodTypeList.get(arg2);
						SelectionListAdapter adapter2 = new SelectionListAdapter(ctx, foodTypeMap.get(selectedFoodType));
						childView.setAdapter(adapter2);
					}
				}
				
			}
		});
        
        if (type == 1) 
        childView.setOnItemClickListener(new OnItemClickListener() {
        	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				// TODO Auto-generated method stub
				
				if(null != handler ) {
						Message msg = new Message();
						msg.what = arg2;
						handler.sendMessage(msg); 
				}
				dialog.dismiss();
			}
		});
        
        dialog.show(); 
    }*/
	
	//创建一个包含自定义view的PopupWindow
	private PopupWindow makePopupWindow(View tagView,  final Handler mHandler) {

		window = new PopupWindow(ctx);
	    
	    LayoutInflater li = LayoutInflater.from(ctx); 
        View view = li.inflate(R.layout.res_book_dialog_list, null); 
        if (type == 1) {
        	view = li.inflate(R.layout.res_book_dialog_list2, null); 
		}
//        progressBar = (ProgressBar)view.findViewById(R.id.drinks_book_dialog_progressbar);
//        progressBar.setVisibility(ProgressBar.VISIBLE);
        dialogListView = (ListView)view.findViewById(R.id.selection_listview);
        final  ListView childView = (ListView)view.findViewById(R.id.selection_child_listview);
    //    initData();
        List<String>list = new ArrayList<String>();
        switch (type) {
		case 0:
			list = disList;
			SelectionListAdapter adapter = new SelectionListAdapter(ctx, list);
	        dialogListView.setAdapter(adapter);
			break;
		case 1:
			 progressBar = (ProgressBar)view.findViewById(R.id.res_book_dialog_progressbar);
			 progressBar.setVisibility(View.VISIBLE);
			break;
		case 2:
			list = orderList;
			adapter = new SelectionListAdapter(ctx, list);
	        dialogListView.setAdapter(adapter);
			break;

		default:
			break;
		}
        
        dialogListView.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				// TODO Auto-generated method stub
				
				if(null != mHandler ) {
					if (type != 1) {
						Message msg = new Message();
						msg.what = arg2;
						mHandler.sendMessage(msg); 
						window.dismiss();
					}else {
						childView.setVisibility(View.VISIBLE);
//						dialogListView.setLayoutParams(new LinearLayout.LayoutParams(200,
//				                LinearLayout.LayoutParams.WRAP_CONTENT));
//						childView.setLayoutParams(new LinearLayout.LayoutParams(200,
//				                LinearLayout.LayoutParams.WRAP_CONTENT));
						selectedFoodType = foodTypeList.get(arg2);
						SelectionListAdapter adapter2 = new SelectionListAdapter(ctx, foodTypeMap.get(selectedFoodType));
						childView.setAdapter(adapter2);
					}
				}
				
			}
		});
        
        if (type == 1) 
            childView.setOnItemClickListener(new OnItemClickListener() {
            	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
    				// TODO Auto-generated method stub
    				
    				if(null != mHandler ) {
    						Message msg = new Message();
    						msg.what = arg2;
    						mHandler.sendMessage(msg); 
    				}
    				window.dismiss();
    			}
    		});
        
	    final Resources res = ctx.getResources();
	    view.setBackgroundColor(res.getColor(R.color.transparent2));
	    view.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
	            LayoutParams.WRAP_CONTENT));
	    //设置PopupWindow显示和隐藏时的动画
	    window.setAnimationStyle(R.style.AnimationFade);
	    //设置PopupWindow的大小（宽度和高度）
	    int width = 0;
	    width = tagView.getWidth() * 2;
	    window.setWidth(width);
	    window.setHeight(LayoutParams.WRAP_CONTENT);
	    //window.setWidth(res.getDimensionPixelSize(R.dimen.page_window_width));
	    //window.setHeight(res.getDimensionPixelSize(R.dimen.page_window_height));
	    //设置PopupWindow的内容view
	    window.setContentView(view);
        //设置PopupWindow外部区域是否可触摸
        window.setOutsideTouchable(true);
        //设置焦点，必须设置，否则listView无法响应
        window.setFocusable(true);
        window.update();
        
	    return window;
	}
	
	
	private final class ComparatorLevel implements Comparator<Restaurant> {
		
		private int flag =1 ;//flag:0表示人均排序，1表示距离排序
		public ComparatorLevel(int flag){
			this.flag = flag;
		}
        @Override
        public int compare(Restaurant p1, Restaurant p2) {
        	if (flag == 0) {
				float avg1 = StringUtils.parseFloat(p1.getAvg());
				float avg2 = StringUtils.parseFloat(p2.getAvg());
				if (avg1 == 0) {
					avg1= 99999;
				}
				if (avg2 == 0) {
					avg2= 99999;
				}
				if (avg1 > avg2) {
					return 1;
				}else if(avg1 == avg2) {
					return  0;
				}else {
					return -1;
				}
			}else {
				float avg1 = StringUtils.parseFloat(p1.getDistance());
				float avg2 = StringUtils.parseFloat(p2.getDistance());
				if (avg1 > avg2) {
					return 1;
				}else if(avg1 == avg2) {
					return  0;
				}else {
					return -1;
				}
			}
        }

    }
	
}
